﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Globalization;

namespace LostLib.Programs
{
	/// <summary>
	/// Describes version dependency
	/// </summary>
	partial class VersionDependency
	{
		public Version Version
		{
			get
			{
				return new Version(Major, Minor);
			}
			set
			{
				if (value == null)
					throw new ArgumentNullException("Version");

				Major = value.Major;
				Minor = value.Minor;
			}
		}

		/// <summary>
		/// Gets all resolvers to this dependency.
		/// </summary>
		/// <returns>A sequence of resolvers.</returns>
		public IEnumerable<AssemblyVersion> Resolvers
		{
			get
			{
				var Assembly = this.AssemblyInfo;

				if (Assembly == null) return new AssemblyVersion[] { };

				switch (DependencyType)
				{
				case "newer":
					return Assembly.AssemblyVersions.Where(version => version.Version >= this.Version);
				default:
					throw new NotSupportedException();
				}
			}
		}
		/// <summary>
		/// Converts Xml representation of version dependency into VersionDependency object.
		/// </summary>
		/// <param name="dependencyNode"></param>
		/// <returns></returns>
		public static VersionDependency Parse(XmlNode dependencyNode)
		{
			var dependencyAssemblyName = dependencyNode.Attributes["assembly"].Value;
			var dependencyVersion = new Version(dependencyNode.Attributes["version"].Value);
			var type = dependencyNode.Attributes["type"].Value;

			var dependency = new VersionDependency() {
				DependencyType = type,
				AssemblyName = dependencyAssemblyName,
				Version = dependencyVersion,
			};

			return dependency;
		}
	}
}
